﻿using NLog;
using System;
using System.Linq;
using Microsoft.SharePoint;
using SharePoint.Utility.Logging;
using System.Globalization;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;

namespace CopyOrdersList.BL.Helpers
{
    public class ViewHelper {
        static ILogger logger = DetailLog.GetLogger;

        public static void RestoreViews(SPWeb web, SPList sourceList, SPList newList) {
            try {
                foreach (var vg in newList.Views.OfType<SPView>().Select(v => v.ID).ToList()) {
                    newList.Views.Delete(vg);
                }
                foreach (SPView view in sourceList.Views) {
                    string title = getTitleView(view.Url);
                    SPView newView = newList.Views.Add(title, view.ViewFields.ToStringCollection(), view.Query, view.RowLimit, view.Paged, view.DefaultView);
                    newView.Title = sourceList.Title;
                    copyTitleResources(view, newView);
                    copyJSLinks(web, view, newView);
                    newView.Update();
                    logger.Debug("The view: " + view.Title + " was added!");
                }
            }
            catch(Exception ex) {
                logger.Error(ex.ToString());
            }
        }

        private static void copyJSLinks(SPWeb web, SPView sourceView, SPView newView) {
            string jsLink = getJSLinkFromView(web, sourceView);
            AssignJsLinkToListViews(web, newView, jsLink);
        }

        private static void copyTitleResources(SPView sourceView, SPView newView) {
            foreach (CultureInfo c in newView.ParentList.ParentWeb.SupportedUICultures) {
                if (sourceView.TitleResource != null) {
                    newView.TitleResource.SetValueForUICulture(c, sourceView.TitleResource.GetValueForUICulture(c));
                    newView.Update();
                }               
            }
        }

        private static void AssignJsLinkToListViews(SPWeb web, SPView view, string jsLink) {
            SPLimitedWebPartManager limitedWebPartManager = null;
            XsltListViewWebPart providerWP = null;
            try {
                limitedWebPartManager = web.GetLimitedWebPartManager(view.Url, PersonalizationScope.Shared);
                providerWP = (from Microsoft.SharePoint.WebPartPages.WebPart webPart in limitedWebPartManager.WebParts where webPart is XsltListViewWebPart select webPart).First() as XsltListViewWebPart;
                providerWP.JSLink = jsLink;
                limitedWebPartManager.SaveChanges(providerWP);
                logger.Trace("jsLink for " + view.Title + " added");
            }
            catch (Exception ex) {
                logger.Error("jsLink " + jsLink + " not assigned! With error: ", ex.ToString());
            }
            finally {
                if (limitedWebPartManager != null) {
                    if (limitedWebPartManager.Web != null) {
                        limitedWebPartManager.Web.Dispose();
                    }
                    limitedWebPartManager.Dispose();
                }
                providerWP.Dispose();
            }
        }

        private static string getJSLinkFromView(SPWeb web, SPView view) {
            SPLimitedWebPartManager limitedWebPartManager = null;
            XsltListViewWebPart providerWP = null;
            try {
                limitedWebPartManager = web.GetLimitedWebPartManager(view.Url, PersonalizationScope.Shared);
                providerWP = (from Microsoft.SharePoint.WebPartPages.WebPart webPart in limitedWebPartManager.WebParts where webPart is XsltListViewWebPart select webPart).First() as XsltListViewWebPart;
                logger.Trace("jsLink for" + view.Title + " got");
                return providerWP.JSLink;
            }
            catch (Exception ex) {
                logger.Error("jsLink " + view.Title + " not got! With error: ", ex.ToString());
                return "";
            }
            finally {
                if (limitedWebPartManager != null) {
                    if (limitedWebPartManager.Web != null) {
                        limitedWebPartManager.Web.Dispose();
                    }
                    limitedWebPartManager.Dispose();
                }
                providerWP.Dispose();
            }
        }

        private static string getTitleView(string url) {
            return url.Split('/').Last().Replace(".aspx", "");
        }
    }
}
